package com.atguigu.flink.streamapi.transform;

import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/11/21
 */
public class Demo10_Process
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           //.global() //全局汇总
           //求所有传感器的水位和
           .process(new ProcessFunction<WaterSensor, String>()
           {
               //每个Task都有自己唯一的ProcessFunction对象，每个对象都有自己唯一的 属性sumVc
               int sumVc = 0;
               /*
                    WaterSensor value: 输入的元素
                     Context ctx： 编程环境，从里面获取一些信息
                     Collector<String> out： 输出
                */
               @Override
               public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                   sumVc += value.getVc();
                   out.collect("当前累积水位:"+sumVc);
               }
           }).setParallelism(1)
           .print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
